/**
 * Created by peizangpin on 2017/5/24.
 */


var editid;
var changesArr = [];

function addChangesRow(row){
    for(var key = 0; key<changesArr.length; key++){
        if(changesArr[key].menuid == row.menuid){;
            changesArr[key] = row;
            return;
        }
    }
    changesArr.push(row);
}
//增加自定义eidtors
$.extend($.fn.datagrid.defaults.editors,{
    editButton:{
        init:function(container, options){
            var okBtn = $('<a>完成</a>');
            var cancelBtn = $('<a>取消</a>');
            okBtn.appendTo(container);
            cancelBtn.appendTo(container);

            cancelBtn.linkbutton({
                iconCls:'icon-cancel'
                ,onClick:function(){
                    $('#menu-treegrid').treegrid('cancelEdit',editid);
                    editid = undefined;
                }
            });
            okBtn.linkbutton({
                iconCls:'icon-ok'
                ,onClick:function(){
                    $('#menu-treegrid').treegrid('endEdit',editid);
                    editid = undefined;
                }
            });
        }
        ,getValue:function (target){
            return;
        }
        ,setValue:function(target,value){
            $(target).val("-");
        }
        ,resize:function(target,width){

        }
    }
});

//给datagrid添加方法
$.extend($.fn.treegrid.methods,{
    removeEditor:function(jq,field){
        var options = jq.treegrid('getColumnOption',field);
        options.editor = {};
    }
    ,addEditor:function(jq,param){
        var field = param.field;
        var editor = param.editor;
        var options = jq.treegrid('getColumnOption',field);
        options.editor = editor;
    }
});


function initTreegrid(){
    $('#menu-treegrid').treegrid({
        title: '菜单数据'
        ,idField:'menuid'
        ,treeField:'menuname'
        ,columns:[[
            {field:'menucode',title:'菜单编码',editor:'textbox'}
            ,{field:'menuname',title:'菜单名称',editor:'textbox'}
            ,{field:'menuUrl',title:'菜单地址',width:300,editor:'textbox',formatter:menuUrlFormatter}
            ,{field:'description',title:'说明',editor:'textbox'}
            ,{field:'operating',title:'操作',formatter:operateingFormatter,editor:'editButton',width:150}
            ,{field:'createTime',title:'创建时间',formatter:formatterDate}
            ,{field:'enableBox',title:'是否启用',formatter:formatterCheckBox,width:100}

        ]]
        ,url:basePath +'menu-action/query-page-menu.html'
        ,method: 'get'
        // ,rownumbers: true
        ,animate: false
        ,collapsible: true
        ,fit:true
        ,toolbar:'#menu-toolbar'
        ,singleSelect:true
        // ,fitColumns:true
        ,loadFilter:function(data){
            if(data){
                for(var key = 0; key < data['total']; key++){
                    data['rows'][key].dnd = true;
                    if(data['rows'][key].enable == 1){
                        data['rows'][key].enableBox = true;
                    }else{
                        data['rows'][key].enableBox = false;
                    }
                }
                return data;
            }
        }
        ,onLoadSuccess:function (row){
            //初始化开关控件
            initSwitchBox();
            $('#menu-treegrid').treegrid('enableDnd', row ? row.menuid : null);
        }
        ,onDragEnter:function(targetRow,sourceRow){
            if(targetRow.menuFolder == 0){
                return false;
            }
        }
        ,onBeforeDrag:function(row){
            if(row.dnd ? row.dnd : null){
                return true;
            }
            return false;
        }
        ,onStopDrag:function(row){
            initSwitchBox();
        }
        ,onDblClickCell:function(field,row){
            if(editid != undefined){
                return;
            }
            if(field == 'operating' && row.dnd == true){
                row.dnd = false;
                if(row.menuFolder == 1){
                    $('#menu-treegrid').treegrid('removeEditor','menuUrl');
                }else{
                    $('#menu-treegrid').treegrid('addEditor',{field:'menuUrl',editor:'textbox'});
                }
                $('#menu-treegrid').treegrid('beginEdit',row.menuid);
                editid = row.menuid;
            }
        }
        ,onEndEdit:function(row,changes){
            row.dnd = true;
            console.info(changes);
            if(!$.isEmptyObject(changes)){
                addChangesRow(row);
                console.info(changesArr);
            }


        }
        ,onAfterEdit:function(row,changes){
            initSwitchBox();
        }
        ,onCancelEdit:function(row){
            initSwitchBox();
            row.dnd = true;
        }
        ,onBeforeSelect:function(row){
            // return false;
        }
    });
}
function operateingFormatter(value,row,index){
    return "双击此处编辑";

}
function formatterCheckBox(value,row) {
    if(row.menuid > 1000000000000000){
        return '<input class = "enableSwitch" value="'+value+'" />';
    }
    return "--";
}
function menuUrlFormatter(value,row){
    if(row.menuFolder == 1){
        return "";
    }
    return value;
}


function initButton(){
    $('#add-menu').linkbutton({
        iconCls:'icon-file'
        ,onClick:function(){
            appendMenu(0);
        }
    });
    $('#add-menuFolder').linkbutton({
        iconCls:'icon-folder'
        ,onClick:function () {
            appendMenu(1);
        }
    });
    $('#save-menu').linkbutton({
        iconCls:'icon-save'
    });
}
function appendMenu(type){
    // type = 1 为添加菜单夹，type = 0 为添加菜单
    if(type != 1 && type != 0){
        return null;
    }
    var selectRow = $('#menu-treegrid').treegrid('getSelected');

    var newRow = null;
    var method = 'append';
    var afterid = null;
    var parentid = 0;
    var tmpMenuid = null;
    var data = null;
    if(!selectRow){
        selectRow = $('#menu-treegrid').treegrid('getRoot');
        method = 'insert';
        newRow = createMenuRow(type,parentid);
        data = {"before":selectRow.menuid,"data":newRow};
    }else{
        parentid = selectRow.menuid;
        if(selectRow.menuFolder == 0){
            parentid = selectRow.parentid;
            method = 'insert';
            afterid = selectRow.menuid;
        }
        newRow = createMenuRow(type,parentid);
        if(afterid != null){
            data = {"after":afterid,"data":newRow};
        }else{
            data = {"parent":parentid,"data":[newRow]};
        }
    }
    $('#menu-treegrid').treegrid(method,data);
    //initSwitchBox();
    $('#menu-treegrid').treegrid('enableDnd', newRow.menuid);
    addChangesRow(newRow);
}

function initSwitchBox(){
    $('.enableSwitch').each(function(index,el){
        var value = $(el).val();
        $(el).switchbutton({
            checked:value
            ,width:90
            ,onText:'启用中'
            ,offText:'停用中'
        });
    });
}

var tmpmenuid = 100;
function getTmpid(){
    if(tmpmenuid == 1000000000000000){
        return null;
    }
    return tmpmenuid++;
}
function createMenuRow(type,parentid){
    if(type != 1 && type != 0){
        return null;
    }
    var re = /^[0-9]+.?[0-9]*$/;


    if(!re.test(parentid)){
        parentid = 0;
    }
    var date = new Date();
    var row = {"createTime":
        {"year":date.getFullYear()
            ,"month":date.getMonth()+1
            ,"day":date.getDate()
            ,"hours":date.getHours()
            ,"minutes":date.getMinutes()
            ,"seconds":date.getSeconds()
            ,"milliseconds":date.getMilliseconds()}
    ,"description":""
        ,"enable":1
        ,"menuFolder":type
        ,"menuUrl":""
        ,"menucode":""
        ,"menuid":getTmpid()
        ,"menuname":""
        ,"parentid":parentid
        ,"state":"closed"
        ,"_parentId":parentid
        ,"dnd":true};
    if(type == 0){
        delete row['state'];
    }
    if(parentid == 0){
        delete row["_parentId"];
    }
    return row;
}